home *** CD-ROM | disk | FTP | other *** search
- From: ChrisHines@msn.com (Chris Hines)
- Subject: Re: C++ beginner quesion on data member access.
- Date: 16 Apr 96 03:52:53 -0700
- References: <4kgb76$r3s@HOPPER.ACM.ORG> <316E7140.C5D@platinum.com>
- Message-ID: <00001a81+0000b22d@msn.com>
- Path: news.msn.com!msn.com
- Newsgroups: comp.lang.c++
- Organization: The Microsoft Network (msn.com)
-
- Michael Scott wrote:
-
- >Ken Varn wrote:
- >>
- >> I have been struggling with the proper way to declare and access data
- >> members in my classes. I was once told that a class should not allow any
- >> data members to be public and that they should only be accessed via member
- >> functions. Why? I know the reasons for declaring private data,
- but what do
- >> I gain if all I am doing is providing a member function to get the private
- >> data or set the private data. i.e. why call a getData() function that
- >> basically just returns the private data member as opposed to just declaring
- >> the pviate data member as public.
- >
- >Classes encapsulate the behavior of an object. Data members
- >represent the "state" of an object. Data access functions
- >provide access to the internal state of an object while allowing
- >the implementation of that state to vary without necessarily
- >changing the interface to the object.
- >
- >Pragmatically speaking though, there are classes and
- >applications where the trade-offs between encapsulation overhead
- >and direct public member access favor the public data.
- >
- >Balancing the trade-offs is what makes programming an art rather
- >than a strict science.
-
- In addition to what Michael says there is at least one other
- compelling reason to provide data access functions: To provide
- read-only access to the data members. As long as the function does
- not return a pointer or reference to the private data member, the
- application outside of the class cannot modify the state of an object
- of the class. (Actually that's not entirely true. One can always
- obtain a pointer to an object and [knowing the offset of the member
- from the beginning of the object] write directly into the object's
- memory space. Doing so is considered highly abusive, however.)
-
- Besides the benefits I can't imagine that there is much loss in terms
- of encapsulation overhead if simple access functions are declared
- inline. In addition, declaring closely related classes or functions
- as friends of your class allow them to access the members of your
- class objects freely without publicizing your members.
-
- -------
- ChrisHines@msn.com
-